//
//  LoginViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddLoginViewController.h"
//#import "JddHomeViewController.h"
#import "JddViewControllerManager.h"
#import "JddCommonFunction.h"
#import "JddGlobalParameter.h"
#import "JddDataParser.h"
#import "JddUserProfile.h"
//#import "AlixPayOrder.h"
//#import "AlixPayResult.h"
//#import "AlixPay.h"
//#import "DataSigner.h"
#import "JddQueryUserInfoOperation.h"
#import "JddQueryAlipayInfoOperation.h"
#import "JddQueryLotteryShopInfoOperation.h"
#import <QuartzCore/QuartzCore.h>

@interface JddLoginViewController ()

@end

@implementation JddLoginViewController

@synthesize userNameTextField;
@synthesize passwordTextField;
@synthesize rememberPasswordSwitch;
@synthesize loginButton;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddLoginViewController);

- (void)QueryUserInfoOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        if (![JddDataParser parseUserInfoResult:result]) {
            if ([[JddViewControllerManager sharedInstance].navigationController topViewController] == [JddLoginViewController sharedInstance]) {
                [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            }
        }else {
            if ([[[JddViewControllerManager sharedInstance].navigationController viewControllers] count] > 1) {
                
                
                if ([[[JddViewControllerManager sharedInstance].navigationController viewControllers] containsObject:[JddRegisterViewController sharedInstance]]) {
                    NSArray *orignalControllers = [[JddViewControllerManager sharedInstance].navigationController viewControllers];
                    NSMutableArray *newControllers = [[NSMutableArray alloc] init];
                    for (UIViewController *inController in orignalControllers) {
                        if (inController != [JddRegisterViewController sharedInstance]) {
                            [newControllers addObject:inController];
                        }
                    }
                    [[JddViewControllerManager sharedInstance].navigationController setViewControllers:newControllers];
                }
                [[JddViewControllerManager sharedInstance].navigationController popViewControllerAnimated:YES];
            } else {
                [[JddViewControllerManager sharedInstance] popToBackViewController];
                
            }
        }
    }
}
- (void)QueryLotteryShopInfoOperationResult:(NSData *)result {
    if (result) {
        if (![JddDataParser parseShopInfoResult:result]) {
//            [JddCommonFunction messageBoxWithMessage:@"获取彩店信息失败"];
        } else {
            [[JddGlobalParameter sharedInstance].dictionary setObject:[JddUserProfile sharedInstance].shopID
                                                               forKey:GLOBAL_PARAMETER_SHOP_ID];
            [[JddGlobalParameter sharedInstance] save];
        }
    } else {
//        [JddCommonFunction messageBoxWithMessage:@"获取彩店信息失败"];
    }
}
#pragma mark ========================需要注意的地方=====================
- (void)LogonOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        NSString *uId = [JddDataParser parseLoginResult:result];
            if (uId.length == 0) {
                [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            }else{
                [JddUserProfile sharedInstance].name = userNameTextField.text;
                [JddUserProfile sharedInstance].password = passwordTextField.text;
                [JddUserProfile sharedInstance].userId = uId;
                
                if ([JddSFHFKeychainUtils getPasswordForUsername:userNameTextField.text andServiceName:@"login" error:nil] != nil) {
                        [JddSFHFKeychainUtils deleteItemForUsername:userNameTextField.text andServiceName:@"login" error:nil];
                    }
                [JddSFHFKeychainUtils storeUsername:userNameTextField.text andPassword:passwordTextField.text forServiceName:@"login" updateExisting:NO error:nil];
                [[JddGlobalParameter sharedInstance].dictionary setObject:userNameTextField.text forKey:GLOBAL_PARAMETER_USER];
                [[JddGlobalParameter sharedInstance].dictionary setObject:passwordTextField.text forKey:GLOBAL_PARAMETER_PASSWORD];
                [[JddGlobalParameter sharedInstance].dictionary setObject:[NSNumber numberWithBool:[rememberPasswordSwitch isOn]] forKey:GLOBAL_PARAMETER_SAVE_PASSWORD];
                [[JddGlobalParameter sharedInstance].dictionary setObject:[NSNumber numberWithBool:[rememberPasswordSwitch isOn]] forKey:GLOBAL_PARAMETER_AUTO_LOGON];
                [[JddGlobalParameter sharedInstance].dictionary setObject:uId forKey:GLOBAL_PARAMETER_USER_ID];
                
                [[JddGlobalParameter sharedInstance] save];
                
                JddQueryUserInfoOperation *operation1 = [[JddQueryUserInfoOperation alloc] init];
                operation1.delegate = self;
                [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation1];
                
                JddQueryLotteryShopInfoOperation *operation2 = [[JddQueryLotteryShopInfoOperation alloc] init];
                operation2.delegate = self;
                [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation2];
            }
        }
        else {
            [JddCommonFunction messageBoxWithMessage:@"连接超时，请重试!"];
        }
}

- (IBAction)loginButtonClicked:(id)sender{
    
    if (![userNameTextField.text length] || ![passwordTextField.text length]) {
        [JddCommonFunction messageBoxWithMessage:NAME_PASSWORD_NOT_ALLOWED_EMPTY];
        return;
    }
    [self hideKeyB];
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    
    JddLogonOperation *operation = [[JddLogonOperation alloc] init];
    operation.delegate = self;
    operation.userName = userNameTextField.text;
    operation.userPassword = passwordTextField.text;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

-(IBAction)editnext:(id)sender{
    [passwordTextField becomeFirstResponder];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    oneTap.delegate = self;
    oneTap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:oneTap];
    
    //[self.navigationItem setTitle:@"欢迎登录玩球球"];
    if (IOS7) {
        [self.navigationItem setTitle:@"欢迎登录"];
    }else{
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:@"欢迎登录"];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
    }

//    //self.navigationItem.hidesBackButton = YES;

    [rememberPasswordSwitch setOn:[JddUserProfile sharedInstance].password != nil];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}

- (void)QueryAlipayInfoOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        if ([JddDataParser paseAlipayInfoResult:result]) {
//            [UserProfile clearMessage];
            [JddCommonFunction setWaitingViewHidden:NO fromController:self];

            JddQueryUserInfoOperation *operation1 = [[JddQueryUserInfoOperation alloc] init];
            operation1.delegate = self;
            [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation1];
        }
        else {
            if (requestAlipayCount == 3) {
                requestAlipayCount = 0;
                [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            }else{
                [JddCommonFunction setWaitingViewHidden:NO fromController:self];
                [self sendAlipayInfoRequest];
            }
        }
    }
}

-(void)queryAlipayInfo :(NSNotification *)note
{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    userId = note.object;
    [self sendAlipayInfoRequest];
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)sendAlipayInfoRequest
{
    [NSThread sleepForTimeInterval:2];
    requestAlipayCount += 1;
    JddQueryAlipayInfoOperation *operation1 = [[JddQueryAlipayInfoOperation alloc] init];
    operation1.alipayID = userId;
    operation1.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation1];
}

-(void)hideKeyB
{
    [self.view endEditing:NO];
}

-(void)hideKeyBoard
{
    [self hideKeyB];
    if (passwordTextField.text == nil||[passwordTextField.text length]==0) {
        passwordTextField.text = [JddSFHFKeychainUtils getPasswordForUsername:userNameTextField.text andServiceName:@"login" error:nil];
    }
}

-(IBAction)ediOver:(id)sender{
    if (passwordTextField.text == nil||[passwordTextField.text length]==0) {
        passwordTextField.text = [JddSFHFKeychainUtils getPasswordForUsername:userNameTextField.text andServiceName:@"login" error:nil];
    }
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return  YES;
}// clear button事件,返回NO过滤之
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}// 'return' key事件.返回NO过滤之

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"Login"];

    [self hideKeyB];
    requestAlipayCount = 0;
    [rememberPasswordSwitch setOn:YES];
    userNameTextField.text = @"";
    passwordTextField.text = @"";
    [self loadTextFieldContent];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"Login"];
}
- (void)loadTextFieldContent
{
    //UITextField 内容水平，垂直居中
    self.userNameTextField.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    self.userNameTextField.contentHorizontalAlignment= UIControlContentHorizontalAlignmentCenter;
    self.userNameTextField.clearsOnBeginEditing = NO;
    self.userNameTextField.tag = 1;
    [self.userNameTextField setDelegate:self];
    [self.userNameTextField setClearButtonMode:UITextFieldViewModeUnlessEditing];
    [self.userNameTextField addTarget:self
                  action:@selector(editnext:)
        forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.userNameTextField addTarget:self
                  action:@selector(ediOver:)
        forControlEvents:UIControlEventEditingDidEnd];
    [self.view addSubview:self.userNameTextField];
    
    self.passwordTextField.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    self.passwordTextField.contentHorizontalAlignment= UIControlContentHorizontalAlignmentCenter;
    self.passwordTextField.clearsOnBeginEditing = NO;
    self.passwordTextField.tag = 2;
    [self.passwordTextField setDelegate:self];
    [self.passwordTextField setClearButtonMode:UITextFieldViewModeUnlessEditing];
    [self.passwordTextField setSecureTextEntry:YES];
    
    [self.passwordTextField addTarget:self
                  action:@selector(loginButtonClicked:)
        forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.passwordTextField setReturnKeyType:UIReturnKeyDone];
    [self.view addSubview:self.passwordTextField];
    
}

-(IBAction)registerBtnClicked:(id)sender
{
    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_REGISTER
                                                            fromController:self
                                                                withObject:nil
                                                               withObject2:nil];
}

- (void)trustload
{    
//    AlixPayOrder *order = [[AlixPayOrder alloc] init];
//    NSString *partner =[[NSBundle mainBundle] objectForInfoDictionaryKey:@"Partner Old"];
//    NSString *seller = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Seller Old"];
//    order.partner = partner;
//    order.seller = seller;
//    NSString* temp= [self trustLogin:partner setuserID:nil];
//    [self lanchstring:temp];
}


- (NSString *)trustLogin:(NSString*) partnerId setuserID:(NSString*) appUserID
{
    NSMutableString* sb = nil;
    sb = [[NSMutableString alloc] init];
    [sb appendString:@"app_name=\"mc\"&biz_type=\"trust_login\"&partner=\""];
    [sb appendString:partnerId];
    
    if (appUserID != nil&& appUserID.length > 0)
        {
        [sb appendString:@"\"&app_userid=\""];
        [sb appendString:appUserID];
        }
    [sb appendString:@"\"&notify_url=\"" ];
    //    [sb appendString:@"http://test.jiangduoduo.com/action/user/member/MobileLoginVerify.ashx"];
    [sb appendString:@"http://www.jiangduoduo.com/action/user/member/MobileLoginVerify.ashx"];
    //    [sb appendString:@"http://221.224.214.35:1111/action/user/member/MobileLoginVerify.ashx"];
    //    [sb appendString:@"http%3A%2F%2Ftest.jiangduoduo.com%2Faction%2Fuser%2Fmember%2FMobileLoginVerify.ashx"];
    //    [sb appendString:@"http%3A%2F%2Fnotify.msp.hk%2Fnotify.htm"];
    
    [sb appendString:@"\""];
	
    return sb;
}

- (void)lanchstring:(NSString*) sb
{
//	NSString *appScheme = @"JiangDuoDuo-IOS"; //应用注册scheme用于安全支付成功后重新唤起商户应用
//    NSString *bankCode = [[NSUserDefaults standardUserDefaults] objectForKey:@"bank_code"];
//    if (bankCode)
//        {
//        NSMutableString *orderSpecTemp = [[NSMutableString alloc] initWithString:sb];
//        [orderSpecTemp appendFormat:@"&appname=\"mc\"&biz_type=\"quickpaypre\"&mspfid=\"creditquickpay:%@\"", bankCode];
//        
//        sb = [NSString stringWithString:orderSpecTemp];
//        }
//    
//	id<DataSigner> signer = CreateRSADataSigner([[NSBundle mainBundle] objectForInfoDictionaryKey:@"RSA private key Old"]);
//	
//	NSString *signedString = [signer signString:sb];
//	NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
//                             sb, signedString, @"RSA"];
//	
//	AlixPay * alixpay = [AlixPay shared];
//	int ret = [alixpay pay:orderString applicationScheme:appScheme];
//	
//	if (ret == kSPErrorAlipayClientNotInstalled) {
//		UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示"
//															 message:@"您还没有安装支付宝的客户端，请先安装。"
//															delegate:self
//												   cancelButtonTitle:@"确定"
//												   otherButtonTitles:nil];
//		[alertView setTag:123];
//		[alertView show];
//	}
//	else if (ret == kSPErrorSignError) {
//		NSLog(@"签名错误！");
//	}else{
//        //监听
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryAlipayInfo:) name:ALIPAY_ID_MESSAGE object:nil];
//    }
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)findPassword:(id)sender {
  
    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOOKFOR_PASSWORD
                                                            fromController:self
                                                                withObject:userNameTextField.text
                                                               withObject2:nil];
    
    
}
@end
